﻿using System;
using System.Windows.Threading;
using System.Windows.Navigation;
using System.Collections.ObjectModel;
using Microsoft.Phone.Controls;
using System.Windows;


/// USING QR CODE LIB
using Microsoft.Devices;
using com.google.zxing;
using com.google.zxing.common;
using com.google.zxing.qrcode;

namespace ScannerDemo
{
    public partial class MainPage
    {
        App App = App.Current as App;
        private readonly DispatcherTimer _timer;
        private readonly ObservableCollection<string> _matches;

        private PhotoCameraLuminanceSource _luminance;
        private QRCodeReader _reader;
        private PhotoCamera _photoCamera;
        
        public MainPage()
        {
            /// Initialize 
            InitializeComponent();
            _matches = new ObservableCollection<string>();
            _matchesList.ItemsSource = _matches;

            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromMilliseconds(250);
            _timer.Tick += (o, arg) => ScanPreviewBuffer();
        }

        /// <summary>
        /// Initialize Camera
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _photoCamera = new PhotoCamera();
            _photoCamera.Initialized += OnPhotoCameraInitialized;            
            _previewVideo.SetSource(_photoCamera);

            CameraButtons.ShutterKeyHalfPressed += (o, arg) => _photoCamera.Focus();

            base.OnNavigatedTo(e);
        }
        /// <summary>
        /// Initialize Camera
        /// </summary>
        /// <param name="e"></param>
        private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e)
        {
            int width = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
            int height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);
            
            _luminance = new PhotoCameraLuminanceSource(width, height);
            _reader = new QRCodeReader();

            Dispatcher.BeginInvoke(() => {
                _previewTransform.Rotation = _photoCamera.Orientation;
                _timer.Start();
            });
            
        }
 
        private void ScanPreviewBuffer()
        {
            try
            {
                _photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);
                var binarizer = new HybridBinarizer(_luminance);
                var binBitmap = new BinaryBitmap(binarizer);
                var result = _reader.decode(binBitmap);
                Dispatcher.BeginInvoke(() => DisplayResult(result.Text));
            }
            catch
            {
            }            
        }
        /// <summary>
        /// Get Data Form QR Code
        /// </summary>
        /// <param name="text"></param>
        private void DisplayResult(string text)
        {
            if (!_matches.Contains(text))
            {

                App.itemId = text;
                //_matches.Add(text);  
                _photoCamera = null;
                _timer.Stop();
                _reader = null;
                _luminance = null;
                //MessageBox.Show(text);
                NavigationService.Navigate(new Uri("/Detail.xaml?text=" + text, UriKind.Relative));
                //MessageBox.Show("Return :"+System.Environment.NewLine + text);
                
            }        
        }
        /// <summary>
        /// Implement BackKeyPress
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
           // RELEASE OBJ
           // _photoCamera.Dispose();
            _photoCamera = null;
            _timer.Stop();
            _reader = null;
            _luminance = null;
            NavigationService.Navigate(new Uri("/Panorama.xaml", UriKind.Relative));
            
        }
        /// <summary>
        /// BUTTON CLICK EVENT
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Click(object sender, RoutedEventArgs e)
        {
            // RELEASE OBJ
            _photoCamera = null;
            _timer.Stop();
            _reader = null;
            _luminance = null;
            App App = App.Current as App;
            App.itemId = tbox.Text;
            NavigationService.Navigate(new Uri("/Detail.xaml?text=" + tbox.Text, UriKind.Relative));
        }

    }
}